<template>
  <div>
    姓名: <input type="text" v-model="name">
    <br><br>
    年龄: <input type="text" v-model="age">
    <br><br>
    性别: <select v-model="sex">
      <option value="男">男</option>
      <option value="女">女</option>
    </select><br><br>
    <button @click="addOrEdit">添加/修改</button>
     <br><br>
    <table>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for=" (item,index) in list" :key="item.id">
          <td>{{index+1}}</td>
          <td>{{item.name}}</td>
          <td>{{item.age}}</td>
          <td>{{item.sex}}</td>
          <td>
            <button @click="del(index)">删除</button> &nbsp;
            <button @click="edit(index)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      list:[
        {
         name:'Tom',
         age:18,
         sex:'女'
         },
         {
         name:'Jone',
         age:20,
         sex:'男'
         }
        ],
        name:'',
        age:'',
        sex:'',
        editIndex:null
    }
  },
  methods: {
    addOrEdit(){
      const obj={id:this.list.length+1,name:this.name,age:this.age,sex:this.sex}
      // console.log(obj);
      if(this.editIndex!==null){
        this.$set(this.list,this.editIndex,obj)
        this.editIndex=null
         this.name='',
        this.age='',
        this.sex=''
      }
      else{
        this.list.push(obj)
        this.name='',
        this.age='',
        this.sex=''
      }
    },
    del(index){
      this.list.splice(index,1)
    },
    edit(index){
    this.name=this.list[index].name
    this.age=this.list[index].age
    this.sex=this.list[index].sex
    this.editIndex=index
    console.log(this.editIndex);
    }
  }
}
</script>

<style>
table{
  width: 500px;
  border: 1px solid black;
  border-collapse: collapse;
}
table,thead,tbody,th,tr,td{
   border: 1px solid black;
}
</style>